<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="elements"
        @submit="handleSearch"
        @reset="handlerReset"
      >
        <Button icon="add" type="plain" @click="handleAdd">新增</Button>
      </FilterForm>
    </Container>
    <Container height="fill">
      <div class="wraper">
        <Table
          :columns="tableColumns"
          :loading="tableLoading"
          :data="tableData"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize,
          }"
          @paginationChange="pageChange"
        >
          <template #status="{ row }">
            <el-switch
              v-model="row.status"
              active-color="#2178FB"
              :active-value="1"
              :inactive-value="0"
              @change="handleSwitch(row)"
            />
          </template>
          <template #caozuo="{ row }">
            <Tooltip
              content="分配权限"
              icon="icon-assignPermissions-o"
              @click="handleShareLimit(row)"
            />
            <Tooltip content="编辑" icon="edit" @click="handleEdit(row)" />
            <Tooltip content="删除" icon="delete" @click="handleDelete(row)" />
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        :title="title"
        :visible.sync="showDrawer"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <el-form
          v-if="showDrawer"
          ref="drawerForm"
          :model="drawerForm"
          :rules="drawerRules"
          label-width="120px"
          size="mini"
          class="demo-drawerForm"
        >
          <el-form-item label="角色：" prop="roleName">
            <el-input
              v-model.trim="drawerForm.roleName"
              placeholder="请输入"
              maxlength="20"
              clearable
            />
          </el-form-item>
          <el-form-item label="是否启用：">
            <el-switch
              v-model="drawerForm.status"
              :width="50"
              active-color="#2178FB"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="备注：">
            <el-input
              v-model.trim="drawerForm.remark"
              type="textarea"
              :rows="6"
              placeholder="请输入"
              maxlength="50"
              clearable
            />
          </el-form-item>
        </el-form>
      </Drawer>
      <!-- 分配权限 -->
      <Drawer
        title="分配操作权限"
        :visible.sync="isShow"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qxLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleQxSubmit"
        @cancel="isShow = false"
      >
        <div class="demo-ruleForm">
          <el-tree
            ref="treeBox"
            :key="treeKey"
            style="overflow-y: auto"
            :data="treeData"
            :default-expanded-keys="defaultExpandId"
            :default-checked-keys="defaultCheckId"
            show-checkbox
            node-key="id"
            :props="defaultProps"
          />
        </div>
      </Drawer>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  selectRoleList,
  saveOrUpdateNew,
  updateRoleStatus,
  removeSysRole,
  addAuthMenu,
  selectSysMenuVO,
  selectMenuId
} from '@/api/roleManage'

export default {
  data() {
    return {
      treeKey: "",
      qxLoading: false,
      defaultExpandId: [],
      defaultCheckId: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      treeData: [],
      isShow: false,
      optionList: [],
      drawerForm: {
        roleName: "",
        remark: "",
        status: 1,
      },
      drawerRules: {
        roleName: [{ required: true, message: "请输入角色", trigger: "blur" }],
      },
      qrLoading: false,
      showDrawer: false,
      title: "",
      tableColumns: [
        {
          title: "角色",
          dataIndex: "roleName",
        },
        {
          title: "备注",
          dataIndex: "remark",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
        },
        {
          title: "是否启用",
          dataIndex: "status",
          type: "otherTag",
        },
        {
          title: "操作",
          dataIndex: "caozuo",
          type: "otherTag",
          width: 160,
        },
      ],
      btnType: 1,
      currentRow: {},
      total: 0,
      pageSize: 100,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      elements: [
        {
          label: "角色",
          type: "input",
          key: "roleName",
          value: "",
          placeholder: "请输入角色",
          width: 180,
        },
      ],
    };
  },
  created() {
    
  },
  methods: {
    // 是否启用
    handleSwitch(row) {
      updateRoleStatus({
        id: row.id,
        status: row.status
      }).then(res => {
        if (res.code === 200) {
          this.getData()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 权限数据
    getRoleMenuTree() {
      const params = {
        menuName: "",
      };
      // this.tableLoading = true
      selectSysMenuVO(params)
        .then(res => {
          // this.tableLoading = false
          if (res.code === 200) {
            this.treeData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          // this.tableLoading = false
        })
    },
    // 分配权限--确认
    handleQxSubmit() {
      const keys = this.$refs.treeBox.getCheckedKeys();
      const halfKeys = this.$refs.treeBox.getHalfCheckedKeys();
      const param = {
        menuIdList: [...keys],
        roleId: this.currentRow?.id,
      };
      this.qxLoading = true
      addAuthMenu(param).then(res => {
        this.qxLoading = false
        if (res.code === 200) {
          this.isShow = false
          this.getData()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleShareLimit(row) {
      // 分配权限
      this.currentRow = row;
      this.defaultExpandId = [];
      this.defaultCheckId = [];
      const result = JSON.parse(JSON.stringify(row));
      this.rowDetails = result;
      this.treeKey = Math.random();
      selectMenuId({
        roleId: row.id
      }).then(res => {
        if (res.code === 200) {
          this.defaultExpandId = res.data
          this.defaultCheckId = res.data
        }
      })
      this.getRoleMenuTree();
      this.isShow = true;
    },
    // 新增、编辑--保存
    handleSubmit() {
      this.$refs['drawerForm'].validate(valid => {
        if (valid) {
          const param = {
            ...this.drawerForm
          }
          if (this.btnType === 2) {
            // 编辑
            param.id = this.currentRow?.id
          }
          this.qrLoading = true
          saveOrUpdateNew(param).then(res => {
            this.qrLoading = false
            if (res.code === 200) {
              this.getData()
              this.showDrawer = false
              this.$message.success(res.msg)
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.currentPage = 1;
      this.getData(value);
    },
    // 重置
    handlerReset(val) {
      this.handleSearch(val);
    },
    handleEdit(row) {
      // 编辑
      this.btnType = 2;
      this.currentRow = row;
      this.handleSetForm(row);
      this.title = "编辑角色";
      this.showDrawer = true;
    },
    handleDelete(row) {
      // 删除
      this.$ckConfirm({
        content: '此操作将删除该条记录，并无法恢复， 是否继续?',
        title: '提示',
        okFn: res => {
          removeSysRole({
            id: row.id
          }).then(res => {
            if (res.code === 200) {
              this.currentPage = 1
              this.getData()
              this.$message.success(res.msg)
            } else {
              this.$message.error(res.msg)
            }
          })
        },
        cancelFn: res => {
          console.log('取消')
        }
      })
    },
    // 新增
    handleAdd() {
      this.btnType = 1;
      this.title = "添加角色";
      this.$handleSetForm(this.drawerForm, 0);
      this.drawerForm.status = 1;
      this.showDrawer = true;
    },
    handleSetForm(row) {
      this.$handleSetForm(this.drawerForm, 1, row);
    },
    // 数据
    getData() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        roleName: this.newCondition.roleName,
      };
      this.tableLoading = true
      selectRoleList(params)
        .then(res => {
          this.tableLoading = false
          if (res.code === 200) {
            this.tableData = res.data.records
            this.total = res.data.total
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    // 分页
    pageChange(payload) {
      this.currentPage = payload.current;
      this.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>
<style lang="less" scoped>
.wraper {
  display: flex;
  height: 100%;
  overflow: hidden;
  .upload-demo {
    .buttons {
      margin: 0px 5px;
      height: 27px;
      margin-top: -1px;
    }
  }
}
.demo-ruleForm {
  padding: 10px 15px;
}
</style>
